package com.skynet.app.api.auth.util;

import com.skynet.app.api.auth.enums.ExpireTimeEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

/**
 * @author Skynet
 * @date 2017年11月23日 12:03
 */
public class JwtTokenUtil {

    private static final SecretKey secretKey = MacProvider.generateKey();

    private JwtTokenUtil() {
    }

    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody();
    }

    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
    }

    private static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + ExpireTimeEnum.ONE_DAY.getValue());
    }
}
